/*
 * Copyright 2012-2013 EZC Group S.A. RCS Luxembourg B140949
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.yobidrive.y3.v1.client.http.handlers;

import java.io.IOException;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.yobidrive.y3.http.HttpResponseHandler;
import com.yobidrive.y3.utils.XMLUtils;
import com.yobidrive.y3.v1.model.GetDriveListResult;
import com.yobidrive.y3.v1.model.GetNodeContentResult;
import com.yobidrive.y3.v1.model.Leaf;
import com.yobidrive.y3.v1.model.Node;
import com.yobidrive.y3.v1.model.RequestChallengeResult;
import com.yobidrive.y3.v1.model.RequestTokenResult;


public class GetNodeContentResponseHandler extends HttpResponseHandler<GetNodeContentResult>{

	static private final Logger logger = Logger.getLogger(GetNodeContentResponseHandler.class);
	
	@Override
	/**
	 * Parse the response to a getNodeContent
	 * <getnodecontentresult>
	 * 	<from></from>
	 *  <limit></limit>
	 *  <hasmore></hasmore>
	 * 	<node>
	 * 		<uid>DDSFQSFQSFQFSF</uid>
	 * 		<name>NAME</name>
	 *  </node>
	 *  ... 
	 * </getnodecontentresult>
	 */
	public GetNodeContentResult handleResponse(HttpResponse response)
			throws ClientProtocolException, IOException {
		
		//Call super to handle every error messages
		super.handleResponse(response);
		
		GetNodeContentResult result = new GetNodeContentResult();
		ArrayList<Node> nodeArray = new ArrayList<Node>();
		
		//Parse XML response
		HttpEntity entity = response.getEntity();
		
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document doc = builder.parse(entity.getContent());
			Element rootElement = doc.getDocumentElement(); 
			
			NodeList children = rootElement.getChildNodes();
			for ( int i=0; i<children.getLength() ; i++) {
				org.w3c.dom.Node childNode = children.item(i);
				
				Node newRespChild = null;
				if ( "node".equals(childNode.getNodeName())) {
					newRespChild = new Node();
				} else if ( "leaf".equals(childNode.getNodeName())) {
					newRespChild = new Leaf();
					((Leaf) newRespChild).lastModified = XMLUtils.getChildText(childNode, "lastmodified");
					((Leaf) newRespChild).version	= XMLUtils.getChildText(childNode, "version");
					((Leaf) newRespChild).size	= XMLUtils.stringToLong(XMLUtils.getChildText(childNode, "size"),-1);
				} else if ( "from".equals(childNode.getNodeName())) {
					result.from = childNode.getTextContent();
					continue;
				} else if ( "limit".equals(childNode.getNodeName())) {
					result.limit = XMLUtils.stringToInt(childNode.getTextContent(),-1);
					continue;
				} else if ( "hasmore".equals(childNode.getNodeName())) {
					result.hasMore = XMLUtils.stringToBoolean(childNode.getTextContent(),false);
					continue;
				} else if ( "isesafe".equals(childNode.getNodeName())) {
					result.isEsafe = XMLUtils.stringToBoolean(childNode.getTextContent(),false);
					continue;
				} else if ( "isowner".equals(childNode.getNodeName())) {
					result.isOwner = XMLUtils.stringToBoolean(childNode.getTextContent(),false);
					continue;
				} else if ( "canpublish".equals(childNode.getNodeName())) {
					result.canPublish = XMLUtils.stringToBoolean(childNode.getTextContent(),false);
					continue;
				} else if ( "publishpolicy".equals(childNode.getNodeName())) {
					result.publishPolicy = childNode.getTextContent();
					continue;
				} else if ( "uid".equals(childNode.getNodeName())) {
					result.uid = childNode.getTextContent();
					continue;
				} else {
					continue;
				}
				newRespChild.name = XMLUtils.getChildText(childNode, "name");
				newRespChild.uid  = XMLUtils.getChildText(childNode, "uid");
				newRespChild.localReadersCount = XMLUtils.stringToInt(XMLUtils.getChildText(childNode, "localreaderscount"),-1);
				newRespChild.localWritersCount = XMLUtils.stringToInt(XMLUtils.getChildText(childNode, "localwriterscount"),-1);
				nodeArray.add(newRespChild);
			}

			Node[] resArray = new Node[nodeArray.size()];
			nodeArray.toArray(resArray);
			result.nodes = resArray;
		} catch (Exception ex) {
			logger.error("Error handling response",ex);
			return null;
		}
		
		return result;
	}

	
	
}
